package com.xie.smfs.event;

import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import com.xie.smfs.registry.ModItems;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.server.network.ServerPlayerEntity;
import com.xie.smfs.common.events.PlayerEvents;

public class PlayerJoinListener {
    public static void register() {
        // 使用1.20.1正确的API
        ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
            ServerPlayerEntity player = handler.getPlayer();

            // 仅首次加入时给予初始物品
            // 使用服务器端数据存储检查初始物品领取状态
            NbtCompound playerData = PlayerEvents.getSpiritAttributes(player);
            if (!playerData.getBoolean("has_received_starter_items")) {
                giveItem(player, new ItemStack(Items.WOODEN_SWORD));
                giveItem(player, new ItemStack(Items.BREAD, 10));
                giveItem(player, new ItemStack(ModItems.SILENT_GHOST_EYE));
                playerData.putBoolean("has_received_starter_items", true);
                PlayerEvents.setSpiritAttributes(player, playerData);
            }
        });
    }

    private static void giveItem(PlayerEntity player, ItemStack stack) {
        if (!player.getInventory().insertStack(stack)) {
            player.dropItem(stack, false);
        }
    }
}